package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;


    private  static  final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    //创建阻塞队列
    private BlockingDeque<VoucherOrder> orderTasks=new LinkedBlockingDeque<>(1024*1024);

    private  static final  ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();

    @PostConstruct
    private void  init()
    {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());

    }


    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {

            while (true)
            {
                try {
                    //获取队列中订单信息
                    VoucherOrder voucherOrder=orderTasks.take();
                    //创建订单
                    hanleVoucherOrder(voucherOrder);

                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
                    log.error("处理订单异常",e);
                }


            }

        }
    }

    private void hanleVoucherOrder(VoucherOrder voucherOrder) {

        Long userId = voucherOrder.getUserId();

//获取锁对象
//        SimpleRedisLock Lock = new SimpleRedisLock("lock:"+userId,stringRedisTemplate);
        RLock Lock = redissonClient.getLock("lock:order:" + userId);

        //调用获取锁的方法
        Boolean isLock = Lock.tryLock();

        if(!isLock)
        {
//            return Result.fail("一人只能下一单！");
            log.error("一人只能下一单！");
            return ;
        }
        try {
             proxy.createVoucherOrder(voucherOrder);
        } finally {
            //释放锁
            Lock.unlock();
        }





    }


    private IVoucherOrderService proxy;
    //查询优惠卷
    @Override
    public Result seckillVoucher(Long voucherId) {

        //获取用户
        Long userId = UserHolder.getUser().getId();

        //执行lua脚本
        Long result =  stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        );

        //判断结果为零
        int r=result.intValue();
        if(r!=0)
        {
            return Result.fail(r==1?"库存不足":"不能重复下单");
        }


        //不为零，代表没有购买资格
        //生成订单id
        long orderId = redisIdWorker.nextId("order");


        //为0，有购买资格把下单信息保存到阻塞队列
        //封装订单信息订单
        VoucherOrder voucherOrder=new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);

        orderTasks.add(voucherOrder);

        proxy = (IVoucherOrderService) AopContext.currentProxy();

        //返回订单ID

        return Result.ok(orderId);



    }



//    @Override
//    @Transactional
//    public Result seckillVoucher(Long voucherId) {
//
//        //查询秒杀优惠卷
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//
//        //判断秒杀是否过期
//        if(beginTime.isAfter(LocalDateTime.now()))
//        {
//            //秒杀未开始
//            return Result.fail("秒杀未开始");
//
//        }
//
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//        if(endTime.isBefore(LocalDateTime.now()))
//        {
//            //秒杀已结束
//            return  Result.fail("秒杀已结束");
//        }
//
//        //查看库存是否充足
//        if(seckillVoucher.getStock()<1)
//        {
//            //库存不足
//            return  Result.fail("库存不足！");
//        }
//
//        //扣减库存,添加乐观锁，解决超卖问题
//        boolean  idSuccess= seckillVoucherService.update()
//                .setSql("stock=stock-1")
//                .eq("voucher_id", voucherId)
//                .gt("stock",0)//添加乐观锁，解决超卖问题
//                .update();
//
//        if(!idSuccess)
//        {
//            return Result.fail("库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
//
//        //获取锁对象
////        SimpleRedisLock Lock = new SimpleRedisLock("lock:"+userId,stringRedisTemplate);
//        RLock Lock = redissonClient.getLock("lock:order:" + userId);
//
//        //调用获取锁的方法
//        Boolean isLock = Lock.tryLock();
//
//        if(!isLock)
//        {
//            return Result.fail("一人只能下一单！");
//        }
//
//
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            //释放锁
//            Lock.unlock();
//        }
//
//
//    }


    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder)
    {
        Long userId = voucherOrder.getUserId();


            //解决一人一单问题
            Integer count = query().eq("user_id", userId).eq("voucher_id", voucherOrder).count();

            if(count>0)
            {
//                return  Result.fail("用户已过下单，不能重复下单！");
                log.error("用户已过下单，不能重复下单！");
                return ;
            }

            //扣减库存
        boolean isSuccess = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherOrder)
                .gt("stock", 0)
                .update();
        if(!isSuccess)
        {
            log.error("库存不足");
            return ;
        }

        //将用户订单保存到数据库中
        save(voucherOrder);

    }







}
